#!/usr/bin/env bash
set -euo pipefail

echo "🚀 多Agent协商一键测试启动"
echo "===================================="

PORTS=(7001 7003 7004 7005 7006)
echo "🧹 清理旧进程..."
for p in "${PORTS[@]}"; do
  if lsof -i :$p >/dev/null 2>&1; then
    fuser -k ${p}/tcp || true
  fi
done
sleep 2

log_dir="logs"
mkdir -p "$log_dir"

start_agent() {
  local name=$1
  local script=$2
  local port=$3
  echo "🚀 启动 ${name} (${port})..."
  nohup uv run python ${script} >"${log_dir}/${name}.log" 2>&1 &
  echo $! >"${log_dir}/${name}.pid"
  sleep 2
  if lsof -i :${port} >/dev/null 2>&1; then
    echo "✅ ${name} 已启动 (端口 ${port})"
  else
    echo "❌ ${name} 启动失败 (端口 ${port} 未监听)" >&2
  fi
}

start_agent "MCPServer" mcp_server.py 7001
# 使用智能天气Agent替换基础版本，提供城市别名与回退能力
start_agent "WeatherAgent" intelligent_weather_agent.py 7003
start_agent "TravelAgent" travel_agent.py 7004
start_agent "RestaurantAgent" restaurant_agent.py 7005
start_agent "CoordinatorAgent" coordinator_agent.py 7006

echo "\n⏳ 等待服务稳定..."
sleep 3

echo "\n📊 端口状态:"
for p in "${PORTS[@]}"; do
  if lsof -i :$p >/dev/null 2>&1; then
    echo "  ✅ $p 监听中"
  else
    echo "  ❌ $p 未启动"
  fi
done

echo "\n🧪 发送协同请求到 CoordinatorAgent..."
REQ='{"message": {"content": {"text": "明天北京有雨, 3天行程, 喜欢历史和美食, 帮我规划景点和餐厅并考虑天气影响"}}}'

HTTP_CODE=$(curl -s -o /tmp/coord_resp.json -w "%{http_code}" -H 'Content-Type: application/json' -d "$REQ" http://localhost:7006/a2a/tasks/send || true)

if [ "$HTTP_CODE" != "200" ]; then
  echo "❌ 协同请求失败 HTTP ${HTTP_CODE}" >&2
  cat /tmp/coord_resp.json || true
  exit 1
fi

echo "✅ 协同请求成功，原始响应已保存: /tmp/coord_resp.json"

echo "\n🧾 抽取核心回复:"
python - <<'PY'
import json,sys
data=json.load(open('/tmp/coord_resp.json'))
try:
    text=data['artifacts'][0]['parts'][0]['text']
    print(text[:1000] + ('...' if len(text)>1000 else ''))
except Exception as e:
    print('解析失败', e)
PY

echo "\n📜 运行协商演示脚本 (生成 agent_negotiation.log)..."
uv run python agent_negotiation_demo.py >/tmp/negotiation_demo.out 2>&1 || true

echo "✅ 协商演示完成，日志末尾预览:"
tail -n 15 agent_negotiation.log || echo "⚠️ 未找到日志"

echo "\n🎯 测试完成。下一步可查看: logs/*.log 或 agent_negotiation.log"
echo "🛑 停止全部: xargs -a logs/*.pid -r kill"
